 ///
 /// @file    reference2.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-04-20 11:22:27
 ///
 
#include <iostream>
using std::cout;
using std::endl;


//值传递,其本质就是进行复制
#if 0
void swap(int x, int y)
{
	int temp = x;
	x = y;
	y = temp;
}
#endif

//地址传递 ==》 值传递
void swap(int * px, int * py)
{
	int temp = *px;
	*px = *py;
	*py = temp;
}

// int & x = num1;
// int & y = num2;
//引用作为函数的参数，引用传递
//好处：不需要进行复制，可以大大提升程序的执行效率
//操作引用就是操作实参本身
void swap(int & x, int & y)
{
	int temp = x;
	x = y;
	y = temp;
}

void test1(const int & x)
{//在使用引用x的过程中，不希望改变x的值
	//x = 10;
}
 
void test0() 
{
	int num1 = 3, num2 = 4;
	cout << "num1:" << num1 << ", num2: " << num2 << endl;
	swap(num1, num2);
	/* swap(&num1, &num2); */
	cout << "num1:" << num1 << ", num2: " << num2 << endl;

} 

int func1()
{
	int number = 1;
	cout << "func1: number :" << number << endl;
	return number;//执行return语句时，这里是要进行复制的
}


int & func2()
{
	int number2 = 10;
	cout << "func2: number2:" << number2 << endl;
	return number2;
}

//全局数组
int arr[5] = {1, 2, 3, 4, 5};
int & func3(int idx)
{
	return arr[idx];
}


int & func4()
{
	int * p = new int(100);
	cout << "func4(): *p = " << *p << endl;
	return *p;
}

void test3()
{
	int a = 1, b = 2, c = 3;
	//将堆空间的变量100复制给了d变量
	int d = func4();
	cout << "d:" << d << endl;
	//delete &d;

	a = b + c + func4();
	cout << "a:" << a << endl;
}

void test2()
{
	//进行了绑定
	int & ref = func3(0);
	ref = 10;
	cout << "ref:" << ref << endl;
	cout << "arr[0]: " << arr[0] << endl;
}
 
int main(void)
{
	/* test0(); */
	/* test2(); */
	test3();
	/* int & ref = func2(); */
	/* ref = 100;//该空间已经被回收了，如果继续进行操作是很危险的 */
	return 0;
}
